package cn.by.wms.javaweb;

import cn.hutool.core.date.StopWatch;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.connector.RequestFacade;
import org.slf4j.MDC;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@WebFilter("/api/*")
@Slf4j
public class TraceIdFilter implements Filter {
    private static final String MDC_TRACEID = "traceId";

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String traceId = httpServletRequest.getHeader(MDC_TRACEID);

        if(ObjectUtil.isEmpty(traceId)){
            traceId = IdUtil.fastUUID();
        }
        MDC.put(MDC_TRACEID,traceId);

        log.debug("TraceIdFilter 获取到前端传的traceId是 {}",traceId);
        chain.doFilter(request, response);

    }
}
